package com.luo.chengrui.module.sa.service.auth;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.extra.spring.SpringUtil;
import cn.iocoder.yudao.framework.mybatis.core.util.MyBatisUtils;
import com.luo.chengrui.module.sa.controller.admin.role.vo.RoleFolderUserPageReqVO;
import com.luo.chengrui.module.sa.convert.role.RoleFolderUserConvert;
import com.luo.chengrui.module.sa.dal.dataobject.auth.AuthorizeViewDO;
import com.luo.chengrui.module.sa.dal.dataobject.role.PermissionDO;
import com.luo.chengrui.module.sa.dal.dataobject.role.RoleFolderUserDO;
import com.luo.chengrui.module.sa.dal.dataobject.role.RoleFolderUserViewDO;
import com.luo.chengrui.module.sa.dal.redis.RedisKeyConstants;
import com.luo.chengrui.module.sa.service.auth.AuthorizeService;
import com.luo.chengrui.module.sa.service.role.PermissionServiceImpl;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import org.springframework.validation.annotation.Validated;

import java.util.*;
import java.util.stream.Collectors;

import com.luo.chengrui.module.sa.controller.admin.auth.vo.*;
import com.luo.chengrui.module.sa.dal.dataobject.auth.AuthorizeDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;

import com.luo.chengrui.module.sa.convert.auth.AuthorizeConvert;
import com.luo.chengrui.module.sa.dal.mysql.auth.AuthorizeMapper;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertSet;
import static com.luo.chengrui.module.sa.enums.ErrorCodeConstants.*;;

/**
 * 角色授权  Service 实现类
 *
 * @author 诚睿
 */
@Service
@Validated
public class AuthorizeServiceImpl implements AuthorizeService {

    @Resource
    private AuthorizeMapper authorizeMapper;

    private AuthorizeServiceImpl getSelf() {
        return SpringUtil.getBean(getClass());
    }


    @Override
    @CacheEvict(value = RedisKeyConstants.SA_PSM_AUTH_LIST, key = "#createReqVO.orgFullId")
    public String createAuthorize(AuthorizeCreateReqVO createReqVO) {
        // 插入
        String roleIds = createReqVO.getRoleId();
        String[] roleIdsArray = roleIds.split(",");

        // 获取已有角色数据
        Set<String> existsRoleIds = convertSet(authorizeMapper.selectListByFullId(createReqVO.getOrgFullId()), AuthorizeDO::getRoleId);
        // 计算新增和删除的菜单编号
        Collection<String> createRoleId = CollUtil.subtract(Arrays.stream(roleIdsArray).collect(Collectors.toSet()), existsRoleIds);
        List<AuthorizeDO> authorizeList = new ArrayList<>();

        if (createRoleId != null && createRoleId.size() > 0) {
            for (String roleId : createRoleId) {
                AuthorizeDO authorize = AuthorizeConvert.INSTANCE.convert(createReqVO);
                authorize.setRoleId(roleId);
                authorizeList.add(authorize);
            }
        }
        authorizeMapper.insertBatch(authorizeList);
        // 返回
        return "";
    }

    @Override
    public void updateAuthorize(AuthorizeUpdateReqVO updateReqVO) {
        // 校验存在
        validateAuthorizeExists(updateReqVO.getId());
        // 更新
        AuthorizeDO updateObj = AuthorizeConvert.INSTANCE.convert(updateReqVO);
        authorizeMapper.updateById(updateObj);
    }

    @Override
    public void deleteAuthorize(String id) {
        // 校验存在
        AuthorizeDO dao = authorizeMapper.selectById(id);
        if (dao == null) {
            throw exception(AUTHORIZE_NOT_EXISTS);
        }
        // 删除
        authorizeMapper.deleteById(id);
        // 更新缓存
        getSelf().clearAuthorizeCacheByFullId(dao.getOrgFullId());
        getSelf().selectListCustomizeByFullIdFromCache(dao.getOrgFullId());

    }

    private void validateAuthorizeExists(String id) {
        if (authorizeMapper.selectById(id) == null) {
            throw exception(AUTHORIZE_NOT_EXISTS);
        }
    }

    @Override
    @CacheEvict(value = RedisKeyConstants.SA_PSM_AUTH_LIST, key = "#fullid")
    public void clearAuthorizeCacheByFullId(String fullid) {
    }

    @Override
    public AuthorizeDO getAuthorize(String id) {
        return authorizeMapper.selectById(id);
    }

    @Override
    public List<AuthorizeDO> getAuthorizeList(Collection<String> ids) {
        return authorizeMapper.selectBatchIds(ids);
    }

    @Override
    public PageResult<AuthorizeDO> getAuthorizePage(AuthorizePageReqVO pageReqVO) {
        return authorizeMapper.selectPage(pageReqVO);
    }

    @Override
    public PageResult<AuthorizeViewDO> selectPageCustomize(AuthorizePageReqVO pageVO) {
        IPage<T> mpPage = MyBatisUtils.buildPage(pageVO);
        authorizeMapper.selectPageCustomize(mpPage, pageVO);
        // 转换返回
        return new PageResult(mpPage.getRecords(), mpPage.getTotal());
    }


    @Override
    @Cacheable(value = RedisKeyConstants.SA_PSM_AUTH_LIST, key = "#fullId")
    public List<AuthorizeViewDO> selectListCustomizeByFullIdFromCache(String fullId) {
        return authorizeMapper.selectListCustomize(fullId);
    }

    @Override
    public List<AuthorizeDO> getAuthorizeList(AuthorizeExportReqVO exportReqVO) {
        return authorizeMapper.selectList(exportReqVO);
    }

}
